/**
 * Copyright (c) 2015-present, MaxLeapMobile. All rights reserved. ---- This source code is licensed
 * under the BSD-style license found in the LICENSE file in the root directory of this source tree.
 * An additional grant of patent rights can be found in the PATENTS file in the same directory.
 */
package com.dl.mian.http;

import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.xlife.shuili.http.Model.HttpResult;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class HttpResponseAESInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url=request.url().toString();
        Response response = chain.proceed(request);

        Log.d("TAG", "code     =  : " + response.code());
        Log.d("TAG", "message  =  : " + response.message());
        Log.d("TAG", "protocol =  : " + response.protocol());

        if (response.body() != null && response.body().contentType() != null) {
            MediaType mediaType = response.body().contentType();
            String string = response.body().string();
            Log.d("TAG", "mediaType =  :  " + mediaType.toString());
            Log.d("TAG", "string    =  : " + string);
            HttpResult httpResult=GsonUtil.gson().fromJson(string, HttpResult.class);
            try {

                String data=AESEncryptUtils.decrypt(httpResult.getData().toString().replace("\n",""),"4%ZkP!@g5LKcf9Ut");
                Object json = new JSONTokener(data).nextValue();

//                httpResult.setData(json);//JSONObject和JsonObject的区别
                if(json instanceof JSONObject){
                    httpResult.setData(GsonUtil.gson().fromJson(data, JsonObject.class));
//                    httpResult.setData((JSONObject)json);
                    //further actions on jsonObjects
                    //...
                }else if (json instanceof JSONArray) {
                    httpResult.setData(GsonUtil.gson().fromJson(data, JsonArray.class));
//                    JSONArray jsonArray = (JSONArray) json;
                    //further actions on jsonArray
                }


                Log.d("AESD", "正常异常    =  : " + url+"   :::"+string);
//                httpResult.setData(GsonUtil.gson().fromJson(data, JsonObject.class));
            }catch (Exception e){
                e.printStackTrace();
                Log.d("AESD", "解密异常    =  : " + url+"   :::"+string);
            }

            ResponseBody responseBody = ResponseBody.create(mediaType, GsonUtil.gson().toJson(httpResult));
            return response.newBuilder().body(responseBody).build();
        } else {
            return response;
        }
    }
}
